import React, { Component } from 'react'
import { Button, Modal, Card, Dropdown, List, Empty, Menu, message, Result, Spin, Typography, Row, Col, Progress, Tooltip } from 'antd'
import { UserOutlined, ExclamationCircleOutlined, DownOutlined, KeyOutlined, CheckCircleTwoTone } from '@ant-design/icons'
import Cookies from 'js-cookie'
import { reqCheckPaperInfo, reqConfirmEnd, reqGetPaperInfo } from '../../api'

import './index.less'

const { confirm, error, warning } = Modal
const { Text } = Typography

//试卷列表页面
export default class Paper extends Component {

    state = {
        loading: false,
        fullName: '',
        jobTitle: '',
        gender: '男',
        PaperInfoViewModels: [],
        schedule: '',
        examProcess: null
    }

    async componentDidMount() {
        await this.getPaperList('first')

        const { schedule, PaperInfoViewModels } = this.state

        let doneCount = 0, examingCount = 0, waitingCount = 0, allCount = PaperInfoViewModels.length

        if (schedule && schedule !== '已结束') {
            for (let item of PaperInfoViewModels) {
                if (item.status === '考试中') {
                    examingCount++
                } else if (item.testedTimes === 0) {
                    waitingCount++
                } else {
                    doneCount++
                }
            }

            let donePer = 0, doneAndExamPer = 0
            if (allCount) {
                donePer = Math.round(doneCount / allCount * 100)
                doneAndExamPer = Math.round((doneCount + examingCount) / allCount * 100)
            }

            this.setState({
                examProcess: {
                    doneCount,
                    examingCount,
                    waitingCount,
                    donePer,
                    doneAndExamPer,
                    allCount
                }
            })
        }

        // if (schedule && schedule !== '已结束') {
        //     // 标识是否都答完一次
        //     let isFlag = true
        //     for (let v of PaperInfoViewModels) {
        //         if (!v.testedTimes) {
        //             isFlag = false
        //         }
        //     }
        //     if (!isFlag) {
        //         warning({
        //             title: '您已答完全部试卷，请确认考试结束'
        //         })
        //     }
        // }
        this.saver = setInterval(() => {
            this.getPaperList()
        }, 60000);
    }

    //loading变更
    changeLoading = (isLoading) => {
        this.setState({
            loading: isLoading
        })
    }

    //获取试卷列表
    getPaperList = async (type) => {
        if (type === 'first') {
            this.changeLoading(true)
        }

        try {
            const res = await reqGetPaperInfo(new Date().getTime())
            const { success, msg, response } = res.data
            if (success) {
                const { fullName, jobTitle, gender, PaperInfoViewModels, schedule } = response
                this.setState({
                    fullName,
                    jobTitle,
                    gender,
                    PaperInfoViewModels,
                    schedule
                })
            } else {
                message.error(msg)
                this.props.history.replace('/login')
            }

            this.changeLoading(false)
        } catch (err) {
            this.changeLoading(false)
            clearInterval(this.saver)
            if (err.response) {
                const { status } = err.response
                if (status === 401) {
                    // message.error('您的登陆信息已过期, 请重新登陆!', 5)
                    error({
                        title: '您的登陆信息已过期，请重新登陆!'
                    })
                    this.props.history.replace('/login')
                } else if (status === 429) {
                    alert('访问过于频繁, 请稍后尝试!')
                } else if (status === 404) {
                    alert('服务器出现异常!')
                } else {
                    alert(err)
                }
            } else {
                alert(err)
            }
        }
    }

    //退出登陆
    skipToLogin = () => {
        Cookies.remove('answerToken')
        this.props.history.replace('/login')
    }

    //返回上一页
    backToAdmin = () => {
        this.props.history.replace('/admin')
    }

    //获取tag样式
    getStatusClass = (status) => {
        let className = ''
        switch (status) {
            case '考试中':
                className = 'exam-status-red'
                break;
            case '待考试':
                className = 'exam-status-green'
                break;
            case '待批改':
                className = 'exam-status-orange'
                break;
            case '不合格':
                className = 'exam-status-fixred'
                break;
            case '合格':
                className = 'exam-status-fixgreen'
                break;
            default:
                break;
        }

        return className
    }

    //开始答题
    startAnswer = async (item) => {
        const { status, paperTemplateId, ongoingPaperViewModel } = item
        if (status === '待考试') {
            this.changeLoading(true)
            try {
                const res = await reqCheckPaperInfo(paperTemplateId)
                const { success, msg, response } = res.data
                if (success) {
                    const { id } = response
                    this.props.history.replace(`/answer/${paperTemplateId}/start/${id}`)

                } else {
                    message.warning(msg)
                    this.getPaperList('first')
                }
            } catch (err) {
                this.changeLoading(false)
                if (err.response) {
                    const { status } = err.response
                    if (status === 401) {
                        // message.error('您的登陆信息已过期, 请重新登陆!', 5)
                        error({
                            title: '您的登陆信息已过期，请重新登陆!'
                        })
                        this.props.history.replace('/login')
                    } else if (status === 429) {
                        alert('访问过于频繁, 请稍后尝试!')
                    } else if (status === 404) {
                        alert('服务器出现异常!')
                    } else {
                        alert(err)
                    }
                } else {
                    alert(err)
                }
            }
        } else if (status === '考试中') {
            this.props.history.replace(`/answer/${ongoingPaperViewModel.paperId}/continue/0`)
        }
    }

    //点击确认结束按钮
    confirmEnd = () => {
        confirm({
            title: '您确定已完成全部答题吗?',
            content: <span style={{ color: 'red' }}>注:确认后不能再作答!</span>,
            icon: <ExclamationCircleOutlined />,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                this.candidateConfirm()
            }
        })
    }

    //real结束
    candidateConfirm = async () => {
        this.changeLoading(true)
        try {
            const res = await reqConfirmEnd()
            const { success, msg } = res.data
            if (success) {
                message.success(msg)
                this.getPaperList()
            } else {
                message.warning(msg)
                this.changeLoading(false)
            }
        } catch (err) {
            this.changeLoading(false)
            if (err.response) {
                const { status } = err.response
                if (status === 401) {
                    // message.error('您的登陆信息已过期, 请重新登陆!', 5)
                    error({
                        title: '您的登陆信息已过期，请重新登陆!'
                    })
                    this.props.history.replace('/login')
                } else if (status === 429) {
                    alert('访问过于频繁, 请稍后尝试!')
                } else if (status === 404) {
                    alert('服务器出现异常!')
                } else {
                    alert(err)
                }
            } else {
                alert(err)
            }
        }
    }

    componentWillUnmount() {
        this.changeLoading(false)
        clearInterval(this.saver)
    }

    render() {
        const { loading, fullName, jobTitle, PaperInfoViewModels, schedule, gender, examProcess } = this.state
        const menu = (
            <Menu>
                <Menu.Item key='1' icon={<KeyOutlined />}>
                    <a onClick={this.skipToLogin}>退出登陆</a>
                </Menu.Item>
            </Menu>
        )

        return (
            <div className='paper'>
                <Spin spinning={loading}>
                    {/* <div className="bg2"></div> */}
                    <header className="header">
                        <Dropdown overlay={menu} arrow>
                            <Button className="header-btn" type='text' icon={<UserOutlined />}>
                                {fullName} <DownOutlined />
                            </Button>
                        </Dropdown>
                    </header>
                    {!schedule ? (
                        <Card className='info-empty'>
                            <Empty style={{ marginTop: 200 }} />
                        </Card>
                    ) : (
                        schedule === '已结束' ? (
                            <Card className='info-end'>
                                <Result
                                    icon={<CheckCircleTwoTone style={{ fontSize: 120 }} />}
                                    title='您已完成答题,请等待主管面试!'
                                    extra={[
                                        <Button onClick={this.backToAdmin} key='back' type='primary' size='large'>返回上一页</Button>
                                    ]}
                                    className='info-end-result'
                                />
                            </Card>
                        ) : (
                            <div className="info-detail-card-wrapper">
                                <Row gutter={32}>
                                    <Col span={18}>
                                        <Card
                                            className='info-detail'
                                            title={
                                                <div className='interviewer-tips'>
                                                    您好，<span className='interviewer-infos'>{fullName}</span>{gender === '男' ? '先生' : '女士'}，您应聘的岗位是 <span className="interviewer-infos">{jobTitle}</span>
                                                </div>
                                            }
                                            bodyStyle={{ padding: 0 }}
                                        >
                                            <div className="paper-list-wrapper scroll-container">
                                                <List
                                                    bordered
                                                    dataSource={PaperInfoViewModels}
                                                    renderItem={item => (
                                                        <List.Item
                                                            actions={[
                                                                <Button onClick={() => this.startAnswer(item)} type='primary' disabled={item.disable}>开始答题</Button>
                                                            ]}
                                                        >
                                                            <List.Item.Meta
                                                                title={
                                                                    <>
                                                                        <span className='paper-title'><Text type='danger'>{item.isCommon ? '(通用) ' : '(专业) '}</Text>{item.paperTitle}</span><span className={this.getStatusClass(item.status)}>{item.status}</span> {item.status === '待考试' && item.testedTimes > 0 && <span style={{ color: '#ff962a', marginLeft: 15 }}>上次答题未合格，您可重新答题!</span>}
                                                                    </>
                                                                }
                                                                description={
                                                                    <div className='exam-info-detail'>
                                                                        <p>总分：{item.totalScore}分 | 及格分数：{item.passScore}分</p>
                                                                        <p>考试限时：{item.answerTimeLimit}分钟</p>
                                                                        <p>考试限制次数：{item.answerTimes}次 | 已考次数：{item.testedTimes}次</p>
                                                                    </div>
                                                                }
                                                            />
                                                        </List.Item>
                                                    )}
                                                />
                                            </div>
                                            <Card bordered={false} className='my-confirm-card' bodyStyle={{ padding: '12px 25px' }}>
                                                <Button onClick={this.confirmEnd} type='primary' className='my-confirm-end'>确认考试结束</Button>
                                            </Card>
                                        </Card>
                                    </Col>
                                    <Col span={6}>
                                        <Card
                                            title='答题进度'
                                            hoverable
                                            bodyStyle={{
                                                display: 'flex',
                                                flexFlow: 'column',
                                                alignItems: 'center'
                                            }}
                                        >
                                            <div className='exam-process-tips'>
                                                <span className="tips-success">
                                                </span>
                                                <span>已完成</span>
                                                <span className="tips-examing">
                                                </span>
                                                <span>考试中</span>
                                            </div>
                                            {examProcess && (
                                                <Tooltip title={`${examProcess.doneCount}份已完成 / ${examProcess.examingCount}份考试中 / ${examProcess.waitingCount}份待考试`}>
                                                    <Progress type='circle' percent={examProcess.doneAndExamPer} success={{ percent: examProcess.donePer }} strokeColor='#ec5953' className='my-exam-process' />
                                                </Tooltip>
                                            )}
                                        </Card>
                                    </Col>
                                </Row>
                            </div>
                            // <Card
                            //     className='info-detail'
                            //     title={
                            //         <div className='interviewer-tips'>
                            //             您好，<span className='interviewer-infos'>{fullName}</span>{gender === '男' ? '先生' : '女士'}，您应聘的岗位是 <span className="interviewer-infos">{jobTitle}</span>
                            //         </div>
                            //     }
                            //     bodyStyle={{ padding: 0 }}
                            // >
                            //     <div className="paper-list-wrapper scroll-container">
                            //         <List
                            //             bordered
                            //             dataSource={PaperInfoViewModels}
                            //             renderItem={item => (
                            //                 <List.Item
                            //                     actions={[
                            //                         <Button onClick={() => this.startAnswer(item)} type='primary' disabled={item.disable}>开始答题</Button>
                            //                     ]}
                            //                 >
                            //                     <List.Item.Meta
                            //                         title={
                            //                             <>
                            //                                 <span className='paper-title'><Text type='danger'>{item.isCommon ? '(通用) ' : '(专业) '}</Text>{item.paperTitle}</span><span className={this.getStatusClass(item.status)}>{item.status}</span> {item.status === '待考试' && item.testedTimes > 0 && <span style={{ color: '#ff962a', marginLeft: 15 }}>上次答题未合格，您可重新答题!</span>}
                            //                             </>
                            //                         }
                            //                         description={
                            //                             <div className='exam-info-detail'>
                            //                                 <p>总分：{item.totalScore}分 | 及格分数：{item.passScore}分</p>
                            //                                 <p>考试限时：{item.answerTimeLimit}分钟</p>
                            //                                 <p>考试限制次数：{item.answerTimes}次 | 已考次数：{item.testedTimes}次</p>
                            //                             </div>
                            //                         }
                            //                     />
                            //                 </List.Item>
                            //             )}
                            //         />
                            //     </div>
                            //     <Card bordered={false} className='my-confirm-card' bodyStyle={{ padding: '12px 65px' }}>
                            //         <Button onClick={this.confirmEnd} type='primary' className='my-confirm-end'>确认考试结束</Button>
                            //     </Card>

                            // </Card>
                        )
                    )}
                </Spin>
            </div>
        )
    }
}